from selenium import webdriver
from selenium.common import NoSuchElementException
from selenium.webdriver.common.by import By
from time import sleep
from os import listdir, getcwd
from config import (file_url_config,
                    gylz_config,
                    gygx_config)
from selenium.common import exceptions
from utils import file_utils, yzm_utils
from logs.set_logfile import logger
import shutil
from exception.scraping_exception import scraping_exception
from clean_data.guoyao_clean import clean_data


# 国药广西和国药柳州共用
def get_guoyao_data(username, password, login_name='', file_title=''):
    start_time = gygx_config.query_start_time
    end_time = gygx_config.query_end_time
    if login_name == '国药柳州':
        start_time = gylz_config.query_start_time
        end_time = gylz_config.query_end_time
    options = webdriver.ChromeOptions()
    options.add_experimental_option("prefs", {
        # D:\scraping\pythonProject\scraping
        "download.default_directory": file_url_config.download_selenium_excel_file_url,
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "safebrowsing.disable_download_protection": True,
        "download_restrictions": 0})
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_argument('disable-javascript')
    driver = webdriver.Chrome(options)
    # 最大化浏览器窗口
    driver.maximize_window()
    # 打开网址
    driver.get(gylz_config.login_url)
    sleep(4)

    # 1. 输入用户名
    driver.find_element(By.XPATH, '//*[@id="username"]').send_keys(username)
    # 2. 输入密码
    driver.find_element(By.XPATH,'//*[@id="password"]').send_keys(password)
    while True:
        # 3. 处理验证码 以及输入验证码
        captcha_text = yzm_utils.handle_yzm(driver, driver.find_element(By.XPATH, '//*[@id="code_img"]'))
        sleep(5)
        driver.find_element(By.XPATH, '//*[@id="random_code"]').send_keys(captcha_text)
        sleep(1)
        # 4. 点击登陆
        driver.find_element(By.XPATH,'/html/body/div/div/div[2]/form/a').click()
        sleep(5)
        # 验证码错误之后一直尝试
        n = 1

        try:
            alert = driver.switch_to.alert
            if alert.text == '验证码错误!':
                logger.warning(f"第{n}次尝试, {login_name}验证码错误!")
                alert.accept()
                # 清空验证码
                driver.find_element(By.XPATH, '//*[@id="random_code"]').clear()
                # 点击验证码刷新
                driver.find_element(By.XPATH, '//*[@id="code_img"]').click()
                sleep(5)
                n += 1
                if n == 6:
                    driver.quit()
                    msg = f"多次尝试识别验证码失败！"
                    logger.warning(msg)
                    raise scraping_exception(msg)
                continue
        except exceptions.NoAlertPresentException:
            break
    logger.info("验证码识别成功!")
    sleep(10)
    # 5. 点击流向管理
    driver.find_element(By.XPATH, '//*[@id="header"]/div[3]/div/div/div[2]/div/div/div[1]/ul/li[2]/a').click()
    sleep(5)

    driver.switch_to.frame(0)

    # 6. 设置查询的参数
    # 清空开始时间
    driver.find_element(By.XPATH, '/html/body/div/div/div[2]/div[2]/div/form/table/tbody/tr[2]/td[3]/input').clear()
    # 输入开始时间
    driver.find_element(By.XPATH, '/html/body/div/div/div[2]/div[2]/div/form/table/tbody/tr[2]/td[3]/input').send_keys(
        start_time)
    # 清空结束时间
    driver.find_element(By.XPATH, '/html/body/div/div/div[2]/div[2]/div/form/table/tbody/tr[2]/td[4]/input').clear()
    # 输入结束时间
    driver.find_element(By.XPATH, '/html/body/div/div/div[2]/div[2]/div/form/table/tbody/tr[2]/td[4]/input').send_keys(
        end_time)
    sleep(5)

    # 7. 点击查询

    driver.find_element(By.XPATH, '/html/body/div/div/div[2]/div[2]/div/form/table/tbody/tr[2]/td[5]/button[1]').click()
    # driver.find_element(By.XPATH, '/html/body/div/div/div[2]/div[2]/div/form/table/tbody/tr[2]/td[5]/button[1]').click()
    sleep(5)

    file_list = listdir(file_url_config.download_selenium_excel_file_url)

    # 8. 点击导出
    driver.find_element(By.XPATH, '/html/body/div/div/div[3]/div[1]/div/div[2]/div/a').click()
    sleep(5)

    # 国药的网站 如果查询之后 没有数据 是不让导出的
    try:
        driver.find_element(By.XPATH, '//*[@id="popup_ok"]').click()
        handle_data_empty(file_title=file_title)
        # logger.info(f"{login_name}暂无数据")
    except NoSuchElementException:
        # 用没下载之前的列表和下载之后的列表做对比 判断下载有没有完成
        files = file_utils.check_downfile(file_list)
        # 下载好之后 重命名文件保存起来
        file_utils.rename_file_title(
            source_dir=file_url_config.download_selenium_excel_file_url,
            destination_dir=file_url_config.download_excel_file_url,
            files=files,
            new_filename=file_title
        )
    finally:
        driver.switch_to.default_content()
        driver.quit()


# 如果查询出来没有数据 单独弄一个空的表格
def handle_data_empty(file_title):
    source_path = f"{file_url_config.download_empty_excel_file_url}\\{file_title}"
    destination_path = f"{file_url_config.download_excel_file_url}\\{file_title}"
    destination_path2 = f"{file_url_config.download_selenium_excel_file_url}\\{file_title}"
    shutil.copy2(source_path, destination_path)
    shutil.copy2(source_path, destination_path2)


def scraping():
    # 国药柳州
    try:
        file_utils.delete_file(gylz_config.gylz_error_file_url)
        file_utils.delete_file(gylz_config.selenium_excel_file_url)
        file_utils.delete_file(gylz_config.excel_file_url)
        logger.info("开始获取国药柳州销售数据！")
        get_guoyao_data(
             username=gylz_config.username,
             password=gylz_config.password,
             login_name='国药柳州',
             file_title=gylz_config.gylz_excel_name)
        logger.info("国药柳州数据获取成功！")
        logger.info("国药柳州开始数据清洗！")
        clean_data(gylz_config.selenium_excel_file_url, gylz_config.excel_file_url, '国药柳州')
        logger.info("国药柳州数据清洗成功！")
    except Exception as e:
        logger.error("国药柳州导出报错!")
        logger.error(e)

        file_utils.delete_file(gylz_config.selenium_excel_file_url)
        file_utils.delete_file(gylz_config.excel_file_url)
        file_utils.scraping_error(file_url=gylz_config.gylz_error_file_url, log_msg=e)
    sleep(5)
    # 国药广西
    try:
        file_utils.delete_file(gygx_config.gygx_error_file_url)
        file_utils.delete_file(gygx_config.selenium_excel_file_url)
        file_utils.delete_file(gygx_config.excel_file_url)
        logger.info("开始获取国药广西销售数据！")
        get_guoyao_data(
            username=gygx_config.username,
            password=gygx_config.password,
            login_name='国药广西',
            file_title=gygx_config.gygx_excel_name
        )
        logger.info("国药广西数据获取成功!")
        logger.info("国药广西开始清洗！")
        clean_data(gygx_config.selenium_excel_file_url, gygx_config.excel_file_url, '国药广西')
        logger.info("国药广西清洗成功！")
    except Exception as e:
        logger.error("国药广西导出报错!")
        logger.error(e)
        file_utils.delete_file(gygx_config.selenium_excel_file_url)
        file_utils.delete_file(gygx_config.excel_file_url)
        file_utils.scraping_error(file_url=gygx_config.gygx_error_file_url, log_msg=e)


if __name__ == '__main__':

    # 今天的文件没有创建才可以调用这个方法
    file_utils.create_today_dir()
    scraping()
    # clean_data(gylz_config.selenium_excel_file_url, gylz_config.excel_file_url, '国药柳州')
    # clean_data(gygx_config.selenium_excel_file_url, gygx_config.excel_file_url, '国药广西')


